#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Módulos 
import sys, gtk, pygame, utils, objetos
from pygame.locals import *

# Constantes

# Clases
# ---------------------------------------------------------------------
        
class Linea:
	def __init__(self,texto,posx,posy):
		self.text,self.rect = utils.textotls(texto, posx,posy,14,(0,0,0))

class Sticker(pygame.sprite.Sprite):
	def __init__(self,posx,posy,url,valor,seccion):
		self.image = utils.load_image(url,True)
		self.rect = self.image.get_rect()
		self.rect.centerx = posx
		self.rect.centery = posy
		self.x_ini = posx
		self.y_ini = posy
		self.valor = valor
		self.seccion = seccion
		self.drag = False
		self.correcto = False 
		self.sonido_correcto = pygame.mixer.Sound("sounds/click.wav")
		self.sonido_fallo = pygame.mixer.Sound("sounds/fallo.wav")
	def display(self,screen):
	    if(self.correcto == False):
			screen.blit(self.image, self.rect)

# Clase del lugar donde debe ser colocada la letra de la palabra a ordenar
class Match:
	def __init__(self,posx,posy,url,valor,seccion):
		self.image = utils.load_image(url,True)
		self.rect = self.image.get_rect()
		self.rect.centerx = posx
		self.rect.centery = posy
		self.valor = valor
		self.posx = posx
		self.posy = posy
		self.ocupado = False
		self.seccion = seccion
	

# ---------------------------------------------------------------------

def detectar_arrastre(stickers):
	x,y = pygame.mouse.get_pos()
	for item in stickers:
		if(item.rect.collidepoint(pygame.mouse.get_pos()) and item.correcto == False):
			item.drag = True
			

def soltar(stickers, stickers_match,seccion):
	for sticker in stickers:
		if sticker.drag == True:
			sticker.drag = False
			#print("Suelta letra")
			for match in stickers_match:
				# si esta en el lugar correcto fija la letra en cuestion en esa posicion
				if sticker.valor == match.valor and abs(sticker.rect.centerx - match.posx) < 10 and abs(sticker.rect.centery - match.posy) < 10 and match.ocupado == False and seccion == match.seccion:
					sticker.rect.centerx = match.posx
					sticker.rect.centery = match.posy
					sticker.correcto = True
					#print("iguales "+letra.valor+"-"+match.valor)
					match.ocupado = True
					sticker.sonido_correcto.play()
					break
			# si no se encuentra en el lugar correcto entonces la letra vuelve a la posicion original		
			if(sticker.correcto == False):
					sticker.rect.centerx = sticker.x_ini
					sticker.rect.centery = sticker.y_ini
					sticker.sonido_fallo.play()
					#print("vuelve a la posicion original")

#mueve las letras si estan siendo arrastradas por el mouse
def actualizar_stickers(stickers):
	for item in stickers:
		if(item.drag == True):
			item.rect.centerx,item.rect.centery = pygame.mouse.get_pos()

# verifica si las palabras estan ordenadas			
def ejercicios_completos(stickers):
	for item in stickers:
		if item.correcto == False:
			return False				
	#print("Palabra ordenada")
	return True	


class BotonRegreso(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = utils.load_image("images/c4_12_regreso.png", True)
        self.sonido = pygame.mixer.Sound("sounds/recycle.wav")
        self.rect = self.image.get_rect()
        self.rect.centerx = 150*utils.RES
        self.rect.centery = 450*utils.RES

# ---------------------------------------------------------------------
def dibujar(screen,cursor_picture, clock):
    salir = 0
    background_image = utils.load_image('images/fondo_4.jpg')
    i= 0
    j= 0
    numero_linea = 1
    btn_adelante = objetos.BotonAdelante()
    btn_atras = objetos.BotonAtras()
    btn_regreso = BotonRegreso()
    
    
    clase, clase_rect = utils.texto_clase("Clase 4", 740*utils.RES, 30*utils.RES)
           
    titulo, titulo_rect = utils.texto_titulo("DE VISITA A LA EMBOTELLADORA", 250*utils.RES, 55*utils.RES)
    linea1,linea1_rect = utils.textotlb('Selecciona haciendo click en la parte de la fábrica que quieras visitar', 325*utils.RES,80*utils.RES,18,(255,0,0))
    linea2,linea2_rect = utils.textotlb('para ver el proceso y ubica las piezas en los espacios faltantes.', 300*utils.RES,100*utils.RES,18,(255,0,0))
     
    stickers = (Sticker(590,205,'images/c4_12_1.png',1,1),#bolsas
    Sticker(710,210,'images/c4_12_2.png',2,1),#lavado botellas
    Sticker(635,430,'images/c4_12_3.png',3,3),#camion
    Sticker(575,320,'images/c4_12_4.png',4,3),#encajonado
    Sticker(695,320,'images/c4_12_5.png',5,4),#plastico
    Sticker(600,100,'images/c4_12_6.png',6,4))#tratamiento
    
    
    stickers_match = (Match(130,160,'images/c4_12_1.png',1,1),#bolsas
    Match(400,280,'images/c4_12_2.png',2,1),#lavado botellas
    Match(250,350,'images/c4_12_3.png',3,3),#camion
    Match(270,215,'images/c4_12_4.png',4,3),#encajonado
    Match(350,110,'images/c4_12_5.png',5,4),#plastico
    Match(340,220,'images/c4_12_6.png',6,4))#tratamiento
    
    
    secciones = (Rect(110*utils.RES,120*utils.RES,290*utils.RES,190*utils.RES),
    Rect(110*utils.RES,310*utils.RES,290*utils.RES,190*utils.RES),
    Rect(400*utils.RES,310*utils.RES,290*utils.RES,190*utils.RES),
    Rect(400*utils.RES,120*utils.RES,290*utils.RES,190*utils.RES))
    
    mapa = utils.load_image('images/c4_12_mapa.jpg')
    map1 = utils.load_image('images/c4_12_map1.jpg')
    map2 = utils.load_image('images/c4_12_map2.jpg')
    map3 = utils.load_image('images/c4_12_map3.jpg')
    map4 = utils.load_image('images/c4_12_map4.jpg')
    seccion = 0
    
    
    while salir == 0:
    
    	# Pump GTK messages.sub
		while gtk.events_pending():
			gtk.main_iteration()
			
		for eventos in pygame.event.get():
			if eventos.type == QUIT:
				sys.exit(0)
			elif eventos.type == pygame.VIDEORESIZE:
			   pygame.display.set_mode(eventos.size, pygame.RESIZABLE)	
			elif eventos.type == MOUSEBUTTONDOWN:
				if seccion == 0:
					for i in range(4):
						if secciones[i].collidepoint(pygame.mouse.get_pos()):
							seccion = i+1	
					if btn_adelante.rect.collidepoint(pygame.mouse.get_pos()):
						salir = 9
						btn_adelante.sonido.play()	
					elif btn_atras.rect.collidepoint(pygame.mouse.get_pos()):
						salir = 7					
						btn_atras.sonido.play()				
				if btn_regreso.rect.collidepoint(pygame.mouse.get_pos()):
					seccion = 0
					btn_regreso.sonido.play()	
				detectar_arrastre(stickers)	
			elif eventos.type == MOUSEBUTTONUP:
				soltar(stickers,stickers_match,seccion)			

		# Realiza la animacion del texto
		
		actualizar_stickers(stickers)		
		# Realiza la animacion del texto
		
		#completo = ejercicios_completos(stickers)				
		
		screen.blit(background_image, (0, 0))
		screen.blit(clase, clase_rect)
		
		if seccion == 0:
			screen.blit(mapa, (120*utils.RES, 100*utils.RES))
			screen.blit(titulo, titulo_rect)
			screen.blit(linea1,linea1_rect)
			screen.blit(linea2,linea2_rect)
			screen.blit(btn_adelante.image, btn_adelante.rect)
			screen.blit(btn_atras.image, btn_atras.rect)
		elif seccion == 1:
			screen.blit(map1, (32*utils.RES, 50*utils.RES))
		elif seccion == 2:
			screen.blit(map2, (32*utils.RES, 50*utils.RES))
		elif seccion == 3:
			screen.blit(map3, (32*utils.RES, 50*utils.RES))
		elif seccion == 4:
			screen.blit(map4, (32*utils.RES, 50*utils.RES))			

		if seccion > 0:
			for sticker in stickers:
				if sticker.correcto == False:
					sticker.display(screen)
			screen.blit(btn_regreso.image, btn_regreso.rect)
		
		for sticker in stickers_match:
			if sticker.seccion == seccion and sticker.ocupado:
				screen.blit(sticker.image, sticker.rect)
		
		screen.blit(cursor_picture, pygame.mouse.get_pos())
		pygame.display.flip()

		# Try to stay at 30 FPS
		clock.tick(30)
                	 
    return salir

# This function is called when the game is run directly from the command line:
# ./TestGame.py 
def main():
	
	pygame.init()
	screen = pygame.display.set_mode((int(800*utils.RES), int(520*utils.RES)), pygame.RESIZABLE) #pygame.display.get_surface() #

	# Fake a Sugar cursor for the pyGame canvas area
	pygame.mouse.set_cursor((8,8),(0,0),(0,0,0,0,0,0,0,0),(0,0,0,0,0,0,0,0))
	cursor_picture = pygame.image.load('images/standardcursor.png')
	cursor_picture.convert_alpha() 
	clock = pygame.time.Clock()
	dibujar(screen,cursor_picture,clock)

if __name__ == '__main__':
   main()
